<script lang="ts" setup>
import { onMounted, ref, watch, computed } from 'vue';
import {
  getConfigTypeSelectList,
  getVideoList,
  getItemImage
} from '@/service/api';
import { ConfigurationTypeEnum } from '@/constants/business';
import { $t } from '@/locales';
import { useLoading } from '~/packages/hooks';

const { loading, startLoading, endLoading } = useLoading();
const videoList = ref<Api.Jellyfin.Info | null>(null);
const selectValue = ref<string>('');
const jellyFinList = ref<Api.Basics.SelectItem<string>[] | null>([]);
const searchKeyword = ref('');
const showDetailModal = ref(false);
const currentItem = ref<Api.Jellyfin.ItemInfo | null>(null);

// 分类过滤选项
const filterOptions = computed(() => [
  { label: $t('page.jellyfin.filter.all'), value: 'all' },
  { label: $t('page.jellyfin.filter.movie'), value: 'movie' },
  { label: $t('page.jellyfin.filter.tvshow'), value: 'tvshow' },
  { label: $t('page.jellyfin.filter.anime'), value: 'anime' }
]);
const selectedFilter = ref('all');

// 排序选项
const sortOptions = computed(() => [
  { label: $t('page.jellyfin.sort.nameAsc'), value: 'name-asc' },
  { label: $t('page.jellyfin.sort.nameDesc'), value: 'name-desc' },
  { label: $t('page.jellyfin.sort.dateAsc'), value: 'date-asc' },
  { label: $t('page.jellyfin.sort.dateDesc'), value: 'date-desc' }
]);
const selectedSort = ref('name-asc');

// 添加分页相关状态
const currentPage = ref(1);
const pageSize = ref(40);

// 过滤和排序后的列表
const filteredVideoList = computed(() => {
  if (!videoList.value?.items) return [];

  let filtered = videoList.value.items;

  // 根据类型过滤
  if (selectedFilter.value !== 'all') {
    filtered = filtered.filter((item) => {
      switch (selectedFilter.value) {
        case 'movie':
          return item.type === 'Movie';
        case 'tvshow':
          return item.type === 'Series';
        case 'anime':
          return item.type === 'Series' && item.genres?.includes('Anime');
        default:
          return true;
      }
    });
  }

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(
      (item) =>
        item.name.toLowerCase().includes(keyword) ||
        item.overview?.toLowerCase().includes(keyword)
    );
  }

  return filtered;
});

// 修改计算属性��添加分页
const paginatedVideoList = computed(() => {
  const filtered = filteredVideoList.value;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filtered.slice(start, end);
});

const getDropdownMenu = async () => {
  try {
    startLoading();
    const res = await getConfigTypeSelectList(ConfigurationTypeEnum.Jellyfin);
    jellyFinList.value = res.data;
    if (jellyFinList.value?.length) {
      selectValue.value = jellyFinList.value[0].value;
    }
  } finally {
    endLoading();
  }
};

const getList = async () => {
  try {
    startLoading();
    const res = await getVideoList(selectValue.value, {
      sortBy: selectedSort.value.split('-')[0],
      sortOrder:
        selectedSort.value.split('-')[1] === 'asc' ? 'Ascending' : 'Descending',
      mediaTypes:
        selectedFilter.value === 'all' ? undefined : selectedFilter.value,
      searchTerm: searchKeyword.value || undefined
    });
    videoList.value = res.data;
  } finally {
    endLoading();
  }
};

// 显示详情
const showDetail = (item: Api.Jellyfin.ItemInfo) => {
  currentItem.value = item;
  showDetailModal.value = true;
};

const query = () => {
  getList();
};

watch(selectValue, () => {
  query();
});

onMounted(() => {
  getDropdownMenu();
});

// 添加新的状态
const showSubList = ref(false);
const subListData = ref<Api.Jellyfin.ItemInfo[]>([]);
const currentParent = ref<Api.Jellyfin.ItemInfo | null>(null);

// 获取子列表数据
const getSubList = async (item: Api.Jellyfin.ItemInfo) => {
  try {
    startLoading();
    const res = await getVideoList(item.id);
    subListData.value = res.data.items;
    currentParent.value = item;
    showSubList.value = true;
  } finally {
    endLoading();
  }
};

// 返回主列表
const backToMain = () => {
  showSubList.value = false;
  subListData.value = [];
  currentParent.value = null;
};

// 获取图片URL
const getImageUrl = async (item: Api.Jellyfin.ItemInfo) => {
  if (!item.imageTags?.Primary) return '/placeholder.jpg';
  try {
    const blob = await getItemImage(selectValue.value, item.id, 'Primary');
    return URL.createObjectURL(blob);
  } catch {
    return '/placeholder.jpg';
  }
};
</script>

<template>
  <div
    class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto"
  >
    <!-- 顶部工具栏 -->
    <NCard :bordered="false" class="mb-4">
      <NSpace vertical>
        <NSpace align="center" justify="space-between">
          <NSpace>
            <NSelect
              v-model:value="selectValue"
              :loading="loading"
              :options="jellyFinList"
              class="min-w-40"
            />
            <NButton :loading="loading" type="primary" @click="query">{{
                $t('common.query')
              }}
            </NButton>
          </NSpace>
          <NSpace>
            <NSelect
              v-model:value="selectedSort"
              :options="sortOptions"
              class="min-w-32"
            />
            <NSelect
              v-model:value="selectedFilter"
              :options="filterOptions"
              class="min-w-32"
            />
            <NInput
              v-model:value="searchKeyword"
              :placeholder="$t('jellyfin.search.placeholder')"
              class="min-w-60"
            >
              <template #prefix>
                <icon-material-symbols:search />
              </template>
            </NInput>
          </NSpace>
        </NSpace>
        <span class="text-gray-500"
        >共 {{ filteredVideoList.length }} 个项目</span
        >
      </NSpace>
    </NCard>

    <!-- 主列表/子列表切换 -->
    <div v-if="showSubList" class="mb-4">
      <NSpace align="center">
        <NButton @click="backToMain">
          <template #icon>
            <icon-material-symbols:arrow-back />
          </template>
          返回
        </NButton>
        <span class="text-lg font-medium">{{ currentParent?.name }}</span>
      </NSpace>
    </div>

    <!-- 网格列表展示 -->
    <NScrollbar class="h-[calc(100vh-200px)]">
      <div
        class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 p-4"
      >
        <template v-if="!showSubList">
          <NCard
            v-for="item in paginatedVideoList"
            :key="item.id"
            class="cursor-pointer hover:shadow-lg transition-all duration-300"
            @click="showDetail(item)"
          >
            <div class="aspect-w-16 aspect-h-9 mb-4">
              <NImage
                :preview-disabled="true"
                :src="getImageUrl(item)"
                class="object-cover rounded w-full h-full"
                fallback-src="/placeholder.jpg"
              />
            </div>
            <h3 class="text-lg font-medium mb-2 truncate">{{ item.name }}</h3>
            <div
              class="flex items-center justify-between text-sm text-gray-500"
            >
              <span class="flex items-center">
                <icon-material-symbols:folder class="mr-1" />
                {{ item.collectionType }}
              </span>
              <span class="flex items-center">
                <icon-material-symbols:calendar-month class="mr-1" />
                {{ new Date(item.dateCreated).toLocaleDateString() }}
              </span>
            </div>
          </NCard>
        </template>

        <template v-else>
          <NCard
            v-for="item in subListData"
            :key="item.id"
            class="cursor-pointer hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1"
            @click="showDetail(item)"
          >
            <div class="aspect-w-16 aspect-h-9 mb-4">
              <NImage
                :preview-disabled="true"
                :src="getImageUrl(item)"
                class="object-cover rounded w-full h-full"
                fallback-src="/placeholder.jpg"
              />
            </div>
            <h3 class="text-lg font-medium mb-2 truncate">{{ item.name }}</h3>
            <div
              class="flex items-center justify-between text-sm text-gray-500"
            >
              <span class="flex items-center">
                <icon-material-symbols:folder class="mr-1" />
                {{ item.collectionType }}
              </span>
              <span class="flex items-center">
                <icon-material-symbols:calendar-month class="mr-1" />
                {{ new Date(item.dateCreated).toLocaleDateString() }}
              </span>
            </div>
          </NCard>
        </template>
      </div>
    </NScrollbar>

    <!-- 添加分页组件 -->
    <div class="flex justify-center mt-4">
      <NPagination
        v-model:page="currentPage"
        :item-count="filteredVideoList.length"
        :page-size="pageSize"
      />
    </div>

    <!-- 详情弹窗 -->
    <NModal
      v-model:show="showDetailModal"
      preset="card"
      style="width: 800px; max-width: 90vw"
    >
      <template #header>
        <div class="flex items-center">
          <h3 class="m-0">{{ currentItem?.name }}</h3>
          <NTag
            :type="currentItem?.type === 'Movie' ? 'success' : 'info'"
            class="ml-2"
          >
            {{ $t(`jellyfin.type.${currentItem?.type?.toLowerCase()}`) }}
          </NTag>
        </div>
      </template>

      <div class="flex gap-4 flex-wrap">
        <div class="w-250px flex-shrink-0">
          <NImage
            :src="currentItem ? getImageUrl(currentItem) : ''"
            class="w-full rounded-lg shadow-lg"
            fallback-src="/placeholder.jpg"
          />
        </div>
        <div class="flex-1 min-w-300px">
          <NDescriptions :column="1" bordered>
            <NDescriptionsItem :label="$t('jellyfin.detail.type')">
              {{ $t(`jellyfin.type.${currentItem?.type?.toLowerCase()}`) }}
            </NDescriptionsItem>
            <NDescriptionsItem :label="$t('jellyfin.detail.year')">
              {{ currentItem?.productionYear }}
            </NDescriptionsItem>
            <NDescriptionsItem :label="$t('jellyfin.detail.overview')">
              {{ currentItem?.overview }}
            </NDescriptionsItem>
            <NDescriptionsItem :label="$t('jellyfin.detail.path')">
              {{ currentItem?.path }}
            </NDescriptionsItem>
          </NDescriptions>
        </div>
      </div>
    </NModal>
  </div>
</template>

<style scoped>
.n-list-item:not(:last-child) {
  border-bottom: 1px solid var(--n-divider-color);
}

.aspect-w-16 {
  position: relative;
  padding-bottom: 56.25%;
}

.aspect-w-16 > * {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
</style>

